import tkinter as tk
from tkinter import messagebox, filedialog, simpledialog,StringVar
import os
import subprocess
import urllib.request
import datetime
import git
import threading
import webbrowser
from bs4 import BeautifulSoup
import urllib.parse
def update_time():
    # 获取当前时间
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 更新标签文本
    label.config(text=current_time)
    # 每隔1秒更新一次时间
    root.after(1000, update_time)
def getpluginurl_thread():
    url = "https://gitee.com/yhArcadia/Yunzai-Bot-plugins-index/blob/main/README.md"
    # 发送请求并获取响应
    response = urllib.request.urlopen(url)
    # 读取响应内容
    html = response.read()
    # 创建BeautifulSoup对象
    soup = BeautifulSoup(html, 'html.parser')
    # 查找第二和第三个tbody标签
    tbody_list = soup.find_all('tbody')[1:4]
    # 存储第一个td内容的列表
    td1_result = []
    # 遍历每个tbody
    for tbody in tbody_list:
        # 查找tbody中的每个tr标签
        tr_list = tbody.find_all('tr')
        for tr in tr_list:
            # 查找第一个td中的a标签
            td1_a = tr.find('td').find('a')
            text = td1_a.text
            link = td1_a['href']
            td1_result.append({text: link})
    root = tk.Tk()
    info_label = tk.Label(root,
                          text="该功能只负责安装插件本体，不负责环境、依赖等安装\n若出现依赖或者环境（如py插件）的报错，请参考该插件的文档进行依赖与环境的安装。")
    info_label.pack(side=tk.TOP, padx=10, pady=10)
    # 创建 Listbox，用来显示插件选项
    plugin_listbox = tk.Listbox(root)
    plugin_listbox = tk.Listbox(root)
    plugin_listbox.pack(side=tk.LEFT, fill=tk.Y)
    # 创建 Scrollbar，与 Listbox 关联
    scroll_bar = tk.Scrollbar(root)
    scroll_bar.pack(side=tk.RIGHT, fill=tk.Y)
    plugin_listbox.config(yscrollcommand=scroll_bar.set)
    scroll_bar.config(command=plugin_listbox.yview)
    # 将插件选项添加到 Listbox 中
    for plugin in td1_result:
        plugin_listbox.insert(tk.END, next(iter(plugin)))
    # 创建按钮，并绑定下载插件的函数
    download_button = tk.Button(root, text="下载", command=lambda: download_plugin(plugin_listbox.get(tk.ACTIVE),td1_result))
    download_button.pack(side=tk.LEFT, padx=10, pady=10)
    root.mainloop()  # 进入主消息循环
def download_plugin(a,b):
    path = tk.filedialog.askdirectory(title="选择喵崽路径")
    for i in b:
        for key in i:
          if a == key:
              url = i[key]
              if a=='椰奶插件 (yenai-plugin)':
                  url = "https://github.com/yeyang52/yenai-plugin"
              elif 'github' in url:
                      target_index = url.find("target=")
                      target_start_index = target_index + len("target=")
                      target = url[target_start_index:]
                      decoded_target = urllib.parse.unquote(target)
                      url = decoded_target
                      url = urllib.parse.unquote(url)
              last_slash_index = url.rfind("/")
              if last_slash_index != -1:
                  content = url[last_slash_index + 1:]
              else:
                  second_last_slash_index = url.rfind("/", 0, len(url) - 1)
                  content = url[second_last_slash_index + 1:]
                  print(content)
              messagebox.showinfo("提示", "开始安装中，在新窗口弹出之前请勿执行新的操作！")
              os.chdir(path)  # 切换到Miao-Yunzai目录
              repo = git.Repo.clone_from(url,
                                         path + f'/plugins/{content}',
                                        depth=1, progress=progress_callback)
              messagebox.showinfo("安装结果", "安装成功！")
def getpluginurl():
    # 下载操作放在一个新的线程中执行
    t = threading.Thread(target=getpluginurl_thread)
    t.start()

def download_nodejs():
    url = "https://nodejs.org/dist/v18.17.0/node-v18.17.0-x64.msi"
    messagebox.showinfo("提示", "即将为您跳转，记得把下载好的的东西放在同一个目录，方便日后寻找。")
    webbrowser.open(url)

def download_git():
    # 下载操作放在一个新的线程中执行
    t = threading.Thread(target=download_git_thread)
    t.start()

# 下载操作的线程函数
def download_git_thread():
    url = "https://github.com/git-for-windows/git/releases/download/v2.41.0.windows.3/Git-2.41.0.3-64-bit.exe"
    messagebox.showinfo("提示", "即将为您跳转，记得把下载好的的东西放在同一个目录，方便日后寻找。")
    webbrowser.open(url)
def progress_callback(op_code, cur_count, max_count=None, message=''):
    if op_code == git.RemoteProgress.COMPRESSING:
        print(f'Compressing objects: {cur_count}/{max_count} ({cur_count / max_count * 100:.2f}%)')
    elif op_code == git.RemoteProgress.RECEIVING:
        print(f'Receiving objects: {cur_count}/{max_count} ({cur_count / max_count * 100:.2f}%)')
def run_git():
    # 下载操作放在一个新的线程中执行
    t = threading.Thread(target=run_git_thread)
    t.start()
def run_git_thread():
    path = tk.filedialog.askdirectory(title="选择路径")
    messagebox.showinfo("提示", "开始安装中，在'安装依赖成功'信息弹出之前请勿执行新的操作！")
    miao_yunzai_path1 = rf'{path}/阴天脚本/'
    miao_yunzai_path = rf'{path}/阴天脚本/Miao-Yunzai'
    if not os.path.exists(miao_yunzai_path1):
        os.makedirs(miao_yunzai_path1)
    if not os.path.exists(miao_yunzai_path):
        os.makedirs(miao_yunzai_path)
    try:
        repo = git.Repo.clone_from('https://gitee.com/yoimiya-kokomi/Miao-Yunzai.git', miao_yunzai_path, depth=1,
                                   progress=progress_callback)
        repo2 = git.Repo.clone_from('https://gitee.com/yoimiya-kokomi/miao-plugin.git',
                                    miao_yunzai_path + '/plugins/miao-plugin', depth=1, progress=progress_callback)

        messagebox.showinfo("安装结果", "安装成功,正在为你自动安装依赖")
        # 在克隆成功后执行额外的命令
        cmd1 = 'npm --registry=https://registry.npmmirror.com install pnpm -g'
        cmd2 = 'pnpm config set registry https://registry.npmmirror.com'
        cmd3 = 'pnpm install -P'
        os.chdir(miao_yunzai_path)  # 切换到Miao-Yunzai目录
        subprocess.run(cmd1, shell=True, check=True)
        subprocess.run(cmd2, shell=True, check=True)
        subprocess.run(cmd3, shell=True, check=True)
        messagebox.showinfo("安装结果", "安装依赖成功")
    except Exception as e:
        messagebox.showinfo("安装结果", "安装失败")
# 下载操作的线程函数
def yilai():
    path = tk.filedialog.askdirectory(title="选择喵崽文件夹路径")
    messagebox.showinfo("提示", "开始修复中，在新窗口弹出之前请勿执行新的操作！")
    cmd1 = 'pnpm config set registry https://registry.npmmirror.com'
    cmd2 = 'pnpm config set puppeteer_download_host=https://registry.npmmirror.com'
    cmd3 = 'pnpm config set node_sqlite3_binary_host_mirror https://npmmirror.com/mirrors/sqlite3'
    cmd4 = 'pnpm i'
    os.chdir(path)  # 切换到Miao-Yunzai目录
    subprocess.run(cmd1, shell=True, check=True)
    subprocess.run(cmd2, shell=True, check=True)
    subprocess.run(cmd3, shell=True, check=True)
    subprocess.run(cmd4, shell=True, check=True)
    messagebox.showinfo("修复结果", "修复成功")

# 下载操作的线程函数
def icqq():
    path = tk.filedialog.askdirectory(title="选择喵崽文件夹路径")
    banben = simpledialog.askstring("输入icqq版本", "请输入需要的icqq版本，示例：0.4.8")
    if banben is None or banben.strip() == "":
        messagebox.showinfo("提示", "已取消更改")
        return
    messagebox.showinfo("提示", "开始安装更改中，在新窗口弹出之前请勿执行新的操作！")
    cmd1 = 'pnpm uninstall icqq'
    cmd2 = f'pnpm add icqq@{banben} -w'
    print(cmd2)
    os.chdir(path)  # 切换到Miao-Yunzai目录
    try:
        subprocess.run(cmd1, shell=True, check=True)
    except subprocess.CalledProcessError as e:
        print(f"执行命令 '{cmd1}' 失败: {e}")

    try:
        subprocess.run(cmd2, shell=True, check=True)
        messagebox.showinfo("更改结果", "更改成功")
    except subprocess.CalledProcessError as e:
        messagebox.showinfo("更改结果", "安装失败")

def download_yt():
    # 下载操作放在一个新的线程中执行
    t = threading.Thread(target=download_yt_thread)
    t.start()

# 下载操作的线程函数
def download_yt_thread():
    path = tk.filedialog.askdirectory(title="选择喵崽文件夹路径")
    messagebox.showinfo("提示", "开始安装中，在新窗口弹出之前请勿执行新的操作！")
    os.chdir(path)  # 切换到Miao-Yunzai目录
    repo = git.Repo.clone_from('https://gitee.com/wan13877501248/y-tian-plugin.git', path+'/plugins/y-tian-plugin',
                               depth=1, progress=progress_callback)
    messagebox.showinfo("安装结果", "安装阴天成功，阴天，启动！")

def pup():
    root = tk.Tk()
    root.withdraw()  # 隐藏窗口
    path = tk.filedialog.askdirectory(title="选择喵崽文件夹路径", parent=None)
    banben = simpledialog.askstring("输入puppeteer版本", "请输入需要的puppeteer版本，推荐：19.8.1", parent=None)

    # 省略后续代码
    if banben is None or banben.strip() == "":
        messagebox.showinfo("提示", "已取消更改")
        return
    messagebox.showinfo("提示", "开始安装更改中，在新窗口弹出之前请勿执行新的操作！")
    cmd1 = 'pnpm uninstall puppeteer'
    cmd2 = f'pnpm add puppeteer@{banben} -w'
    os.chdir(path)  # 切换到Miao-Yunzai目录
    try:
        subprocess.run(cmd1, shell=True, check=True)
    except subprocess.CalledProcessError as e:
        print(f"执行命令 '{cmd1}' 失败: {e}")

    try:
        subprocess.run(cmd2, shell=True, check=True)
        messagebox.showinfo("更改结果", "更改成功")
    except subprocess.CalledProcessError as e:
        messagebox.showinfo("更改结果", "安装失败")
def redis():
    url = "http://download.redis.io/releases/redis-5.0.4.tar.gz"
    messagebox.showinfo("提示", "即将为您跳转，记得把下载好的的东西放在同一个目录，方便日后寻找。")
    webbrowser.open(url)

root = tk.Tk()
root.title("阴天PY脚本@1.0.0（内测）")
root.geometry("820x450") # 设置窗口大小为550X250

download_nodejs_button = tk.Button(root, text="下载Node.js", command=download_nodejs)
download_git_button = tk.Button(root, text="下载Git", command=download_git)
run_git_button = tk.Button(root, text="安装喵崽", command=run_git)
yilai_button = tk.Button(root, text="监听依赖报错", command=yilai)
changeicqq_button = tk.Button(root, text="更改icqq版本", command=icqq)
YT_button = tk.Button(root, text="下载阴天", command=download_yt)
get_plugin_button = tk.Button(root, text="获取插件", command=getpluginurl)
pup_button = tk.Button(root, text="puppeteer版本", command=pup)
redis_button = tk.Button(root, text="下载redis", command=redis)
label = tk.Label(root)
label.pack(side=tk.BOTTOM)

label1 = tk.Label(root, text="阴天图形化脚本1.0.0（内测)\nBY：天球生物")
label1.pack(side=tk.BOTTOM)
# 使用pack布局管理器将按钮居中对齐
download_nodejs_button.pack(side=tk.LEFT, padx=10, pady=10)
download_git_button.pack(side=tk.LEFT, padx=10, pady=10)
run_git_button.pack(side=tk.LEFT, padx=10, pady=10)
yilai_button.pack(side=tk.LEFT, padx=10, pady=10)
changeicqq_button.pack(side=tk.LEFT, padx=10, pady=10)
YT_button.pack(side=tk.LEFT, padx=10, pady=10)
get_plugin_button.pack(side=tk.LEFT, padx=10, pady=10)
pup_button.pack(side=tk.LEFT, padx=10, pady=10)
redis_button.pack(side=tk.LEFT, padx=10, pady=10)
update_time()
root.mainloop()